﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using PetaPoco;
using PmSoft;
using PmSoft.ApplicationContext;
using PmSoft.DBContext;
using PmSoft.Repositories;
using PmSoft.Utilities;

namespace Modules.Commander.Repositories
{
    [UseDI(ServiceLifetime.Scoped)]
    public class CommanderInfoRepository : Repository<CommanderInfo, DefaultDbContext>
    {
        private readonly ILogger logger;
        private readonly IApplicationContext applicationContext;

        public CommanderInfoRepository(DefaultDbContext dbContext, IApplicationContext applicationContext, ILogger<CommanderInfoRepository> logger)
            : base(dbContext, applicationContext)
        {
            this.logger = logger;
            this.applicationContext = applicationContext;
        }

        public bool CodeExists(string code, int? id)
        {
            if (id.HasValue)
                return DbContext.Exists<CommanderInfo>("cardno=@0 and commander_id!=@1", StringUtility.StripSQLInjection(code), id);
            return DbContext.Exists<CommanderInfo>("cardno=@0", StringUtility.StripSQLInjection(code));
        }

        public IPagedList<CommanderInfo> GetCommanders(CommanderQuery query, int pageNum, int pageSize)
        {
            Sql sql = Sql.Builder;
            sql.Select("commander_id")
                .From("commander");
            if (!string.IsNullOrEmpty(query.Keywords))
                sql.Where("(name Like @0 or leader Like @0 or cardno Like @0)", "%" + StringUtility.StripSQLInjection(query.Keywords) + "%");
            if (query.ConstructorId.HasValue)
                sql.Where("constructor_id=@0", query.ConstructorId);
            sql.OrderBy("create_time DESC");
            var result = GetPagingEntities(pageSize, pageNum, sql);
            return result;
        }

        public CommanderInfo? GetCommanderInfo(string cardno)
        {
            Sql sql = Sql.Builder.Select("commander_id").From("commander").Where("cardno=@0", cardno);
            var id = DbContext.FirstOrDefault<int>(sql);
            if (id == 0)
                return null;
            return Get(id);
        }

        public bool UpdateDefaultProjectId(CommanderInfo commanderInfo, int projectId)
        {
            if (commanderInfo == null)
                return false;
            var sql_update = Sql.Builder;
            sql_update.Append("Update commander SET project_id = @0 where commander_id = @1", projectId, commanderInfo.CommanderId);//局部更新数据库
            int affectCount = DbContext.Execute(sql_update);
            if (affectCount > 0)
            {
                commanderInfo.ProjectId = projectId;
                base.OnUpdated(commanderInfo);//更新内存数据
                return true;
            }
            return false;
        }
    }
}